//
//  ZallCheckBox.m
//  ZJS-DRIVER
//
//  Created by so on 16/6/3.
//  Copyright © 2016年 liulei. All rights reserved.
//

#import "ZallCheckBox.h"

@interface ZallCheckBox () {
    NSMutableDictionary *_stateImageDict;
}
@end

@implementation ZallCheckBox
@synthesize imageView = _imageView;

#pragma mark - life cycle
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        _stateImageDict = [[NSMutableDictionary alloc] init];
        _actionBlock = nil;
        [self addSubview:self.imageView];
        [self addTarget:self action:@selector(touched:) forControlEvents:UIControlEventTouchUpInside];
    }
    return (self);
}
#pragma mark -

#pragma mark - override
- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = UIEdgeInsetsInsetRect(self.bounds, self.contentInsets);
}

- (void)setEnabled:(BOOL)enabled {
    [super setEnabled:enabled];
    self.imageView.image = _stateImageDict[@(enabled ? ZallCheckBoxStateNormal : ZallCheckBoxStateDisabled)];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    self.imageView.image = _stateImageDict[@(selected ? ZallCheckBoxStateSelected : ([self isEnabled] ? ZallCheckBoxStateNormal : ZallCheckBoxStateDisabled))];
}
#pragma mark -

#pragma mark - setter
- (void)setImage:(nullable UIImage *)image forState:(ZallCheckBoxState)state {
    if(!image) {
        [_stateImageDict removeObjectForKey:@(state)];
    } else {
        [_stateImageDict setObject:image forKey:@(state)];
        if(ZallCheckBoxStateNormal == state) {
            if(!_stateImageDict[@(ZallCheckBoxStateDisabled)]) {
                [_stateImageDict setObject:image forKey:@(ZallCheckBoxStateDisabled)];
            }
        }
    }
    [self setEnabled:[self isEnabled]];
    [self setSelected:[self isSelected]];
}
#pragma mark -

#pragma mark - getter
- (UIImageView *)imageView {
    if(!_imageView) {
        _imageView = [[UIImageView alloc] init];
    }
    return (_imageView);
}

- (nullable UIImage *)imageForState:(ZallCheckBoxState)state {
    return ([_stateImageDict objectForKey:@(state)]);
}
#pragma mark -

#pragma mark - action
- (void)touched:(id)sender {
    if(self.actionBlock) {
        self.actionBlock(self.boxState);
    }
}
#pragma mark -

@end
